{% extends "base.html" %}

{% block title %}完整碳管理报告{% endblock %}

{% block content %}
<div class="container mt-4 mb-5">
    <!-- 报告编辑工具栏 -->
    <div class="card mb-4">
        <div class="card-body d-flex justify-content-between align-items-center">
            <h4>报告编辑</h4>
            <div class="btn-group">
                <button id="saveReport" class="btn btn-primary">保存报告</button>
                <a href="{{ url_for('report_complete.export', format='word') }}" class="btn btn-success">导出Word</a>
                <a href="{{ url_for('report_complete.export', format='pdf') }}" class="btn btn-danger">导出PDF</a>
            </div>
        </div>
    </div>

    <!-- 报告内容编辑区域 -->
    <div class="report-editor">
        <!-- 1. 封面设计区域 -->
        <div id="coverSection" class="card mb-4 p-5 text-center border-2 border-primary position-relative" style="min-height: 297mm; display: flex; flex-direction: column; justify-content: center;">
            <!-- 添加页眉国家标准编号 -->
            <div style="position: absolute; top: 100px; left: 100px; font-size: 1.5rem;"><strong>GB/T</strong> 32151.29—2024</div>
            <h1 contenteditable="true" class="cover-title mb-3" style="margin-top: 100px; font-size: 3.5rem;">机械设备制造企业温室气体排放报告</h1>
            <!-- <h3 contenteditable="true" class="cover-subtitle text-muted mb-5">2023年度可持续发展报告</h3> -->
            <div class="cover-meta" style="text-align: left; margin-top: 450px; margin-left: 100px; font-size: 2.5rem;">
                <p contenteditable="true" style="font-size: 2rem; margin-bottom: 20px;">报告主体（盖章）：</p>
                <p contenteditable="true" style="font-size: 2rem; margin-bottom: 20px;">报告年度：2025</p>
                <p contenteditable="true" style="font-size: 2rem; margin-bottom: 20px;">编制日期：{{ now.strftime('%Y年%m月%d日') }}</p>
            </div>

        </div>

        <!-- 2. 正文内容区域 -->
        <div id="contentSection" class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5>报告正文</h5>
                <button class="btn btn-sm btn-outline-secondary" onclick="addTextSection()">+ 添加段落</button>
            </div>
            <div class="card-body">
                #这里是一段文字，但是中间有一个变量年份，具体内容如下所示
                #本报告主体核算了         年度温室气体排放量,并填写了相关数据表格, 见表1~表4。现将有关情况报告如下 :
                
                <!-- 一、报告主体基本信息 -->
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5>一、报告主体基本信息</h5>
                        <button id="saveBasicInfo" class="btn btn-sm btn-primary">保存信息</button>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered" id="basicInfoTable">    
                            <tbody>
                                <tr>
                                    <td>主体名称</td>
                                    <td><input type="text" class="form-control" id="entityName" value="{{ report_data.entity_name if report_data else '' }}"></td>
                                    <td>单位性质</td>
                                    <td><input type="text" class="form-control" id="entityType" value="{{ report_data.entity_type if report_data else '' }}"></td>
                                </tr>
                                <tr>
                                    <td>统一社会信用代码</td>
                                    <td><input type="text" class="form-control" id="unifiedSocialCreditCode" value="{{ report_data.unified_social_credit_code if report_data else '' }}"></td>
                                    <td>所属行业</td>
                                    <td><input type="text" class="form-control" id="industry" value="{{ report_data.industry if report_data else '' }}"></td>
                                </tr>
                                <tr>
                                    <td>法定代表人</td>
                                    <td><input type="text" class="form-control" id="legalRepresentative" value="{{ report_data.legal_representative if report_data else '' }}"></td>
                                    <td>主营产品</td>
                                    <td><input type="text" class="form-control" id="mainProducts" value="{{ report_data.main_products if report_data else '' }}"></td>
                                </tr>
                                <tr>
                                    <td>填报负责人</td>
                                    <td><input type="text" class="form-control" id="reportResponsiblePerson" value="{{ report_data.report_responsible_person if report_data else '' }}"></td>
                                    <td>联系人信息</td>
                                    <td><input type="text" class="form-control" id="contactInformation" value="{{ report_data.contact_information if report_data else '' }}"></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <script>
                    // 保存企业基本信息
                    document.getElementById('saveBasicInfo').addEventListener('click', function() {
                        const basicInfo = {
                            entity_name: document.getElementById('entityName').value,
                            entity_type: document.getElementById('entityType').value,
                            unified_social_credit_code: document.getElementById('unifiedSocialCreditCode').value,
                            industry: document.getElementById('industry').value,
                            legal_representative: document.getElementById('legalRepresentative').value,
                            main_products: document.getElementById('mainProducts').value,
                            report_responsible_person: document.getElementById('reportResponsiblePerson').value,
                            contact_information: document.getElementById('contactInformation').value
                        };

                        // 显示加载状态
                        const saveButton = this;
                        const originalText = saveButton.textContent;
                        saveButton.disabled = true;
                        saveButton.textContent = '保存中...';

                        // 发送保存请求
                        // 发送保存请求
                        fetch('/save_basic_info', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify(basicInfo)
                        })
                        .then(response => {
                            // 恢复按钮状态
                            saveButton.disabled = false;
                            saveButton.textContent = originalText;

                            if (!response.ok) {
                                // 获取响应文本以获取更多错误信息
                                return response.text().then(text => {
                                    throw new Error(`服务器响应异常: ${response.status} ${response.statusText}\n${text}`);
                                });
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data.success) {
                                alert('保存成功！');
                                // 可以选择刷新页面或更新显示的数据
                            } else {
                                alert('保存失败：' + data.message);
                            }
                        })
                        .catch(error => {
                            console.error('保存失败:', error);
                            alert('保存时发生错误：' + error.message);
                        });
                    });

                    // 页面加载时加载数据
                    document.addEventListener('DOMContentLoaded', function() {
                        console.log('页面加载完成，开始获取企业基本信息...');
                        // 从数据库获取数据
                        fetch('/get_basic_info')
                        .then(response => {
                            console.log('响应状态:', response.status);
                            if (!response.ok) {
                                throw new Error('网络响应错误: ' + response.status);
                            }
                            return response.json();
                        })
                        .then(data => {
                            console.log('获取数据成功:', data);
                            if (data.success && data.data) {
                                const reportData = data.data;
                                console.log('准备填充表单数据:', reportData);
                                document.getElementById('entityName').value = reportData.entity_name || '';
                                document.getElementById('entityType').value = reportData.entity_type || '';
                                document.getElementById('unifiedSocialCreditCode').value = reportData.unified_social_credit_code || '';
                                document.getElementById('industry').value = reportData.industry || '';
                                document.getElementById('legalRepresentative').value = reportData.legal_representative || '';
                                document.getElementById('mainProducts').value = reportData.main_products || '';
                                document.getElementById('reportResponsiblePerson').value = reportData.report_responsible_person || '';
                                document.getElementById('contactInformation').value = reportData.contact_information || '';
                            } else {
                                console.log('获取数据失败:', data.message || '未知错误');
                                alert('获取数据失败: ' + (data.message || '未知错误'));
                            }
                        })
                        .catch(error => {
                            console.error('Error loading data:', error);
                            alert('加载数据时出错: ' + error.message);
                        });
                    });
                </script>
                
                #这里是固定文字：1、企业核算边界（含工艺流程、排放源识别情况等）
                
                <!-- 图片展示区域 -->
                <div class="image-container mt-3 mb-4">
                    <h5 style="font-size: 12pt; font-weight: bold; margin-bottom: 10px;">企业生产流程图</h5>
                    <!-- 从数据库加载的图片将显示在这里 -->
                    <div id="images-container" class="d-flex flex-wrap gap-3 mb-3"></div>
                     
                    <!-- 插入图片按钮 -->
                    <button id="insert-image-btn" class="btn btn-primary btn-sm" style="font-size: 12pt;">
                        <i class="fas fa-image mr-1"></i> 插入图片
                    </button>
                </div>

                <!-- 图片上传模态框 -->
                <div class="modal fade" id="imageUploadModal" tabindex="-1" role="dialog" aria-labelledby="imageUploadModalLabel" aria-hidden="true">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="imageUploadModalLabel" style="font-size: 14pt;">上传图片</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <div class="form-group">
                                    <label for="image-file" style="font-size: 12pt;">选择图片文件</label>
                                    <input type="file" class="form-control-file" id="image-file" accept="image/*">
                                </div>
                                <div class="form-group">
                                    <label for="image-caption" style="font-size: 12pt;">图片说明</label>
                                    <input type="text" class="form-control" id="image-caption" placeholder="输入图片说明">
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-dismiss="modal" style="font-size: 12pt;">取消</button>
                                <button type="button" id="upload-image-btn" class="btn btn-primary" style="font-size: 12pt;">上传</button>
                            </div>
                        </div>
                    </div>
                </div>

                <script>
                    // 页面加载完成后执行
                    document.addEventListener('DOMContentLoaded', function() {
                        // 加载已有的图片
                        loadImages();

                        // 插入图片按钮点击事件
                        document.getElementById('insert-image-btn').addEventListener('click', function() {
                            // 使用原生JavaScript显示模态框
                            const modal = document.getElementById('imageUploadModal');
                            modal.classList.add('show');
                            modal.style.display = 'block';
                            document.body.classList.add('modal-open');
                        });

                        // 上传图片按钮点击事件
                        document.getElementById('upload-image-btn').addEventListener('click', function() {
                            uploadImage();
                        });
                    });

                    // 从服务器加载图片
                    function loadImages() {
                        fetch('/get_images')
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error(`Network response was not ok: ${response.status} ${response.statusText}`);
                                }
                                return response.json();
                            })
                            .then(data => {
                                const imagesContainer = document.getElementById('images-container');
                                imagesContainer.innerHTML = '';

                                data.images.forEach(image => {
                                    const imageDiv = document.createElement('div');
                                    imageDiv.className = 'image-item position-relative';
                                    imageDiv.style.maxWidth = '200px';
                                    imageDiv.style.margin = '5px';

                                    const img = document.createElement('img');
                                    // 使用后端提供的完整URL，而不是手动构建
                                    img.src = image.url;
                                    img.alt = image.caption || 'Report Image';
                                    img.className = 'img-fluid rounded border';
                                    img.style.maxWidth = '100%';
                                    img.style.height = 'auto';

                                    // 删除按钮
                                    const deleteBtn = document.createElement('button');
                                    deleteBtn.className = 'btn btn-danger btn-sm position-absolute top-0 right-0 m-1';
                                    deleteBtn.innerHTML = '<i class="fas fa-times"></i>';
                                    deleteBtn.onclick = function() {
                                        deleteImage(image.id);
                                    };

                                    imageDiv.appendChild(img);
                                    imageDiv.appendChild(deleteBtn);
                                    imagesContainer.appendChild(imageDiv);
                                });
                            })
                            .catch(error => {
                                console.error('Error loading images:', error);
                                alert('加载图片时出错: ' + error.message);
                            });
                    }

                    // 上传新图片
                    function uploadImage() {
                        const fileInput = document.getElementById('image-file');
                        const captionInput = document.getElementById('image-caption');

                        if (!fileInput.files || fileInput.files.length === 0) {
                            alert('请选择一个图片文件');
                            return;
                        }

                        const file = fileInput.files[0];
                        const caption = captionInput.value;
                        const formData = new FormData();

                        formData.append('file', file);
                        formData.append('caption', caption);
                        formData.append('section_id', 1); // 假设当前部分ID为1，根据实际情况修改

                        fetch('/upload_image', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data.success) {
                                alert('图片上传成功');
                                // 使用原生JavaScript隐藏模态框
                                const modal = document.getElementById('imageUploadModal');
                                modal.classList.remove('show');
                                modal.style.display = 'none';
                                document.body.classList.remove('modal-open');
                                loadImages(); // 重新加载图片

                                // 重置表单
                                fileInput.value = '';
                                captionInput.value = '';
                            } else {
                                alert('图片上传失败: ' + data.message);
                            }
                        })
                        .catch(error => {
                            console.error('Error uploading image:', error);
                            alert('上传图片时出错: ' + error.message);
                        });
                    }

                    // 删除图片
                    function deleteImage(imageId) {
                        if (confirm('确定要删除这张图片吗？')) {
                            fetch(`/delete_image/${imageId}`, {
                                method: 'DELETE'
                            })
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error('Network response was not ok');
                                }
                                return response.json();
                            })
                            .then(data => {
                                if (data.success) {
                                    alert('图片删除成功');
                                    loadImages(); // 重新加载图片
                                } else {
                                    alert('图片删除失败: ' + data.message);
                                }
                            })
                            .catch(error => {
                                console.error('Error deleting image:', error);
                                alert('删除图片时出错: ' + error.message);
                            });
                        }
                    }
                </script>

                <!-- 展示数据库中的段落内容 -->
                {% for section in sections %}
                <div class="card mb-3" data-section-id="{{ section.id }}">
                    <div class="card-body" contenteditable="true">
                        <h4 class="section-title" style="font-size: 14pt; font-weight: bold; font-family: 'Microsoft YaHei', sans-serif;">{{ section.title }}</h4>
                        <div class="section-content" style="font-size: 12pt; font-family: 'Microsoft YaHei', sans-serif; margin-bottom: 12pt; text-indent: 24pt;">{{ section.content }}</div>
                    </div>
                    <div class="card-footer d-flex justify-content-end gap-2">
                        <button class="btn btn-sm btn-outline-success" onclick="saveSection('{{ section.id }}')"><i class="bi bi-save"></i> 保存</button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteSection('{{ section.id }}')"><i class="bi bi-trash"></i> 删除</button>
                    </div>
                </div>
                {% else %}
                <div class="text-muted text-center py-4">
                    <p>暂无段落内容，请点击上方"+ 添加段落"按钮创建</p>
                </div>
                {% endfor %}
            </div>
        </div>

        <!-- 4. 报表整合区域 -->
        <div id="reportsSection" class="card mb-4">
            <div class="card-header">
                <h5>报表选择</h5>
            </div>
            <div class="card-body">
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="annualEmissionReport" checked>
                    <label class="form-check-label" for="annualEmissionReport">
                        年度排放报告
                    </label>
                </div>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="fuelConsumptionReport" checked>
                    <label class="form-check-label" for="fuelConsumptionReport">
                        燃料消耗报告
                    </label>
                </div>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="powerReport" checked>
                    <label class="form-check-label" for="powerReport">
                        电力消耗报告
                    </label>
                </div>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="thermalReport" checked>
                    <label class="form-check-label" for="thermalReport">
                        热力消耗报告
                    </label>
                </div>
                <button class="btn btn-primary mt-2" onclick="refreshReports()">更新报表预览</button>
            </div>
        </div>
    </div>
</div>
<style>
/* 封面样式 */
#coverSection {
    min-height: 297mm; /* A4高度 */
    display: flex;
    flex-direction: column;
    justify-content: flex-start; /* 上版页布局 */
    padding-top: 80mm; /* 上版页中部定位 */
}


/* 图片库样式 */
#imageGallery img {
    max-height: 150px;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 5px;
    cursor: move;
}

/* 预览区域样式 */
#reportPreview {
    min-height: 300px;
    border: 1px dashed #ccc;
    padding: 20px;
}
</style>

<script>
function addTextSection() {
    fetch('/add_section', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            section_type: 'text',
            title: '新段落标题',
            content: '新段落内容...'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const newSection = document.createElement('div');
            newSection.className = 'text-section mb-4 p-3 border rounded';
            newSection.setAttribute('data-section-id', data.section.id);
            
            // 重构HTML结构，分离按钮组
            newSection.innerHTML = `
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                    <div class="section-title" style="font-size: 1.2rem; font-weight: bold; min-width: 200px;">
                        <span contenteditable="true">${data.section.title || '未命名段落'}</span>   
                    </div>
                    <div class="section-header-actions">
                        <button class="btn btn-sm btn-outline-success me-2" onclick="saveSection(${data.section.id})">保存</button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteSection(${data.section.id})">删除</button>
                    </div>
                </div>
                <!-- 将内容区域移出flex容器，实现分行显示 -->
                <div class="section-content" style="margin-top: 15px;">
                    ${data.section.content}
                </div>
                <div class="section-content-actions mt-3">
                    <button class="btn btn-sm btn-outline-primary" onclick="addImageHere(this)">插入图片</button>
                </div>
            `;
            
            document.querySelector('#contentSection .card-body').appendChild(newSection);
        }
    });
}


function deleteSection(sectionId) {
    if (confirm('确定要删除此段落吗？')) {
        fetch(`/delete_section/${sectionId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.querySelector(`[data-section-id="${sectionId}"]`).remove();
            } else {
                alert('删除失败: ' + data.error);
            }
        });
    }
}

function saveSection(sectionId) {
    // 精确定位内容区域，避免包含标题文本
    const contentElement = document.querySelector(`[data-section-id="${sectionId}"] .section-content`);
    // 移除HTML标签，仅保留纯文本内容
    const content = contentElement ? contentElement.textContent.trim() : '';
    // 精确定位标题区域
    const titleElement = document.querySelector(`[data-section-id="${sectionId}"] .section-title`);
    const title = titleElement ? titleElement.textContent.trim() : '';

    fetch('/update_section', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            section_id: sectionId,
            title: title,  // 明确传递标题字段
            content: content  // 明确传递内容字段
        }),
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                throw new Error(`Network response was not ok: ${response.status} ${response.statusText}. Details: ${text}`);
            });
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            alert('段落保存成功');
        } else {
            alert('保存失败: ' + data.error);
        }
    })
    .catch(error => {
        console.error('保存请求失败:', error);
        alert('保存时发生错误');
    });
}
</script>
{% endblock %}
